package com.fxhy.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.beust.jcommander.internal.Lists;
import com.beust.jcommander.internal.Maps;
import com.fxhy.bean.AgentUser;
import com.fxhy.contants.Constants;
import com.fxhy.service.UserService;
import com.fxhy.vo.ResponseBodyEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@Api(value="图片接口")
@RequestMapping("pic")
@Slf4j
public class PicApi {
	@Autowired
	private UserService userService;
	
	 /**
     * 废弃 浏览器下载
     * @param urlString
     * @param fileName
     * @param response
     * @param request
     * @throws Exception
     */
	@ApiOperation("下载图片到客户端本地")
	@RequestMapping(value = "downloadInviteImage", method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity downloadByBrower(String phoneNum,Integer downChoose, String downChooseUrl,HttpServletResponse response,HttpServletRequest request) throws Exception {  
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		if(phoneNum != null && !phoneNum.equals("")){
			AgentUser userInfo = userService.findUserByPhone(phoneNum);
			if(userInfo != null && userInfo.getUserId() != null) {
				if(userInfo.getStatus() == 1){
					if(userInfo != null && userInfo.getIsIdentifi() != -1){
						BufferedInputStream dis = null;
				        BufferedOutputStream fos = null;
				        
				        String fileName = "";
						if(downChoose == 1){
							fileName = "二维码.jpg";
				        }else if(downChoose == 2){
				        	fileName = "效果图1.jpg";
				        }else if(downChoose == 3){
				        	fileName = "效果图2.jpg";
				        }else{
				        	fileName = "二维码.jpg";
				        }
				        try {
				            URL url = new URL(downChooseUrl);
				            response.setContentType("application/x-msdownload;");  
//				            String filename = URLEncoder.encode("邀请效果图", "UTF-8");
				            response.setHeader("Content-disposition", "attachment; filename=" + fileName);  
				            response.setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));  
				             
				            dis = new BufferedInputStream(url.openStream());
				            fos = new BufferedOutputStream(response.getOutputStream());  
				             
				            byte[] buff = new byte[2048];  
				            int bytesRead;  
				            while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {  
				                fos.write(buff, 0, bytesRead);  
				            }  
				        } catch (Exception e) {
				            e.printStackTrace();
				        } finally { 
				            if (dis != null)  
				                dis.close();  
				            if (fos != null)  
				                fos.close();  
				        }
						responseBodyEntity.setState(Constants.SUCCEED);
					}else{
						responseBodyEntity.setData("/login");
						responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
						responseBodyEntity.setState(Constants.FAILURE);
						return responseBodyEntity;
					}
				}else if(userInfo.getStatus() == 0){
					responseBodyEntity.setMsg("你的账号处在冻结期!解冻请联系生产商进行申诉!");
					responseBodyEntity.setState(Constants.FAILURE);
				}else if(userInfo.getStatus() == -1){
					responseBodyEntity.setMsg("账号已处在黑名单! 请遵守规定!");
					responseBodyEntity.setState(Constants.FAILURE);
				}else{
					responseBodyEntity.setMsg("无效账号! 无法登录!");
					responseBodyEntity.setState(Constants.FAILURE);
				}
			}else {
				responseBodyEntity.setMsg("用户登录已失效!");
				responseBodyEntity.setState(Constants.FAILURE);
			}
		}else{
			responseBodyEntity.setMsg("用户登录已失效!");
			responseBodyEntity.setState(Constants.FAILURE);
		}
		return responseBodyEntity;
    }   
	
	@ApiOperation("打包图片zip下载到客户端本地")
	@RequestMapping(value = "downLoadImage", method= {RequestMethod.GET,RequestMethod.POST})
    public void downLoadImage(HttpServletResponse response, String id) throws Exception {
        List<String> urls = Lists.newArrayList();
        urls.add("http://a.hiphotos.baidu.com/image/pic/item/b219ebc4b74543a96a58c53112178a82b801148f.jpg");
 
        Map<String, InputStream> isMap = Maps.newHashMap();
        urls.forEach(urlStr -> {
            String[] fileNameParts = urlStr.split("/");
            String fileName = fileNameParts[fileNameParts.length - 1];
            try {
                URL url = new URL(urlStr);
                URLConnection con = url.openConnection();
                // 设置超时间为3秒
                con.setConnectTimeout(3 * 1000);
                // 防止屏蔽程序抓取而返回403错误
                con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                InputStream is = con.getInputStream();
                isMap.put(fileName, is);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
 
        response.setContentType("application/octet-stream");
        String filename = URLEncoder.encode("邀请效果图", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".zip");
        ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
        isMap.forEach((fileName, is) -> {
            try {
                addToZip(is, zipOut, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        zipOut.flush();
        zipOut.close();
    }
	
	private void addToZip(InputStream is, ZipOutputStream zipOut, String fileName) throws IOException {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        ZipEntry entry = new ZipEntry(fileName);
        zipOut.putNextEntry(entry);
        int len;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) > 0) {
            zipOut.write(buffer, 0, len);
        }
        zipOut.closeEntry();
        is.close();
	}
	
   
	
	/**
	 * 获取流
	 * @param path
	 * @return
	 */
	public static InputStream getInputStream(String path){
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try{
            URL url = new URL(path);
            if (null != url)
            {
                httpURLConnection = (HttpURLConnection) url.openConnection();
                // 设置连接网络的超时时间
                httpURLConnection.setConnectTimeout(5000);
                // 打开输入流
                httpURLConnection.setDoInput(true);
                // 设置本次Http请求使用的方法
                httpURLConnection.setRequestMethod("GET");
                if (200 == httpURLConnection.getResponseCode()){
                    // 从服务器获得一个输入流
                    inputStream = httpURLConnection.getInputStream();
                }
            }
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return inputStream;
    }

	/**
	 * 输出流
	 * @param path
	 * @return
	 */
	public static String saveInputStream(InputStream inputStream,String saveToPath){
        byte[] data = new byte[1024];
        int len = 0;

        FileOutputStream fileOutputStream = null;
        try{
            fileOutputStream = new FileOutputStream(saveToPath);
            while (-1 != (len = inputStream.read(data))){
                fileOutputStream.write(data, 0, len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if(null != inputStream){
                try{
                    inputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(null != fileOutputStream){
                try{
                    fileOutputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return saveToPath;
	 }
}	
